﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility;
using DoubleH.Utility.Configuration;
using System.Net;
using System.Net.Sockets;
using DoubleH.Utility.IO;
using FCNS.Data.Table;
using FCNS.Data;
using System.Data;

/*
 * 服务端自动运行开始网络监测,自动接收客户端传入的文件
 * 客户端获取文件,通过发送请求再打开客户端的网络接口开始接收文件.
 */

namespace DHserver
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        //string processName = "WebDev.WebServer40";
        string processPath = DbDefine.baseDir + "Web\\";
        string serverFile = FCNS.Data.DbDefine.appConfigDir + "server.xml";
        bool loadFileServer = false;
        bool loadHttpServer = false;

        private void InitVar()
        {
            Type t = this.GetType();
            DoubleHConfig.ServerConfig = (ServerConfig)ConfigSerializer.LoadConfig(typeof(ServerConfig),serverFile);
            foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                comboBoxIp.Items.Add(ip.ToString());

            comboBoxIp.Text = DoubleHConfig.ServerConfig.DefaultHost;

            StartFileTransfer();

            if (DoubleHConfig.ServerConfig.AutoWeb)
                StartHttp();
            else
                StopHttp();
        }

        private void InitEvent()
        {
            imageWeb.MouseLeftButtonUp += (ss, ee) =>
                {
                    if (loadHttpServer)
                        StopHttp();
                    else
                        StartHttp();
                };

            comboBoxIp.SelectionChanged += (ss, ee) =>
            {
                DoubleHConfig.ServerConfig.DefaultHost = comboBoxIp.SelectedItem.ToString();
            };

            this.Closing += (ss, ee) => SaveConfig(); 
            buttonClear.Click += (ss, ee) => Clear();
        }

        private void SaveConfig()
        {
            DoubleHConfig.ServerConfig.AutoWeb = loadHttpServer;

            DoubleHConfig.ServerConfig.DefaultHost = comboBoxIp.Text;
            DoubleHConfig.ServerConfig.DefaultHostPort = integerUpDownPort.Value.Value;

            ConfigSerializer.SaveConfig(DoubleHConfig.ServerConfig,serverFile);
        }

        private void Clear()
        {
            return; //需要登录数据库才可以清理
            buttonClear.IsEnabled = false;
            listBoxLog.Items.Insert(0, "开始清理 Data\\ProductS 目录");
            List<string> ok = new List<string>();
            foreach (DataRow row in SQLdata.GetDataRows("select UploadFile from ProductS"))
                ok.Add(row[0] as string);

            foreach(string fi in Directory.GetFiles(DbDefine.dataDir+"ProductS"))
                if (!ok.Contains(System.IO.Path.GetFileName(fi)))
                {
                    try { File.Delete(fi); }
                    catch { listBoxLog.Items.Insert(0,fi + " 无法删除"); }
                }

            buttonClear.IsEnabled = true;
        }

        #region startFileTransfer
        private void StartFileTransfer()
        {
            FileTools ft = new FileTools();
           if (ft.ShareFolder(DbDefine.dataDir, "doubleH$", "use for DHserver"))
            {
                loadFileServer = true;
                imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));
            }
            else
                imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));

        }
        #endregion

        //static Config.ClientConfig GetDefaultConfig()
        //{
        //    return new ClientConfig()
        //    {
        //        IPMClientConfig = new FSLib.IPMessager.Entity.Config
        //        {
        //            Port = 2425,
        //            GroupName = Environment.MachineName,
        //            NickName = Environment.UserName,
        //            ForceOldContract = true,
        //            IgnoreNoAddListFlag = false,
        //            EnableHostNotifyBroadcast = false,
        //            HostName = Environment.MachineName,
        //            AutoReplyWhenAbsence = true,
        //            AutoDetectVersion = true,
        //            BanedHost = new List<string>(),
        //            KeepedHostList = new List<string>(),
        //            BindedIP = IPAddress.Any,
        //            VersionInfo = "程序版本号: " ,
        //            AbsenceSuffix = " [离开]",
        //            Services = ServiceManager.GetServices(new string[] { "addins" }),
        //            EnableBPContinue = true,
        //            TaskKeepTime = 600,
        //            TasksMultiReceiveCount = 1
        //        },
        //        AbsenceMessage = new List<string>()
        //        {
        //            "我有事暂时不在，稍后联系你",
        //            "我吃饭去了！",
        //            "有事启奏 >_< 无事退朝",
        //            "还钱请电话，借钱请关机！"
        //        },

        //        HostGroupConfig = new SerializableDictionary<string, string>(),
        //    };
        //}

        //#region file transfer
        //private void StartFileTransfer()
        //{
        //    if (string.IsNullOrEmpty(comboBoxIp.Text))
        //        return;

        //    loadFileServer = true;
        //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));


        //    //Control.CheckForIllegalCrossThreadCalls = false;
        //    D_ThreadRec _D_ThreadRec = new D_ThreadRec(ThreadRec);
        //    _D_ThreadRec.BeginInvoke(null, null);
        //}

        //private void StopFileTransfer()
        //{
        //    loadFileServer = false;
        //    if (serverSocket != null)
        //        serverSocket.Close();

        //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
        //}

        ///// <summary>
        ///// 监听服务函数
        ///// </summary>
        //private void ThreadRec()
        //{
        //    try
        //    {
        //        IPAddress ip = IPAddress.Parse(DoubleHConfig.ServerConfig.DefaultHost);
        //        IPEndPoint ipe = new IPEndPoint(ip, DoubleHConfig.ServerConfig.DefaultHostPort);
        //        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //        serverSocket.Bind(ipe);
        //        serverSocket.Listen(10);
        //        ErrorS.WriteLogFile("服务器开始监听" + DoubleHConfig.ServerConfig.DefaultHostPort + "端口！");
        //        while (true)
        //        {
        //            if (loadFileServer == true)
        //            {
        //                try
        //                {
        //                    //阻塞监听至到有新的连接
        //                    Socket temp = serverSocket.Accept();
        //                    IPEndPoint clientip = (IPEndPoint)temp.RemoteEndPoint;
        //                    //如果连接上
        //                    if (temp.Connected)
        //                    {
        //                        ServerReceiveFile startThreads = new ServerReceiveFile(temp);
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    if (ex.Message != "一个封锁操作被对 WSACancelBlockingCall 的调用中断。")//断开socket时阻塞监听的报错提示
        //                        MessageBox.Show(ex.Message);
        //                }
        //            }
        //            else
        //            {

        //                serverSocket.Close();
        //                ErrorS.WriteLogFile("停止监听服务！");
        //                break;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageWindow.Show(ex.Message);
        //        ErrorS.WriteLogFile(ex.Message);
        //    }
        //}
        //#endregion

        #region http server
        private void StopHttp()
        {
            //foreach (Process pro in Process.GetProcessesByName(processName))
            //    pro.Close();

            //buttonWeb.Content = "Web已停止";
        }

        private void StartHttp()
        {
            //MessageBox.Show(DoubleHConfig.ServerConfig.HttpPort.ToString());
            //if (!File.Exists(processPath + processName + ".exe"))
            //    MessageWindow.Show("Web服务器丢失");
            //else
            //{
            //    Process.Start(processPath + processName + ".exe", " /path:" + processPath + " /port:" + DoubleHConfig.ServerConfig.HttpPort);
            //    buttonWeb.Content = "Web已启动";
            //}
        }
        #endregion
    }
}
